// 序列检测器


module sequential_detector (input clk,
                            rst_n,
                            in,
                            output reg out);
    reg [3:0] stage,next_stage;
    
    parameter s0 = 4'd0,
    s1 = 4'd1,
    s2 = 4'd2,
    s3 = 4'd3,
    s4 = 4'd4,
    s5 = 4'd5,
    s6 = 4'd6,
    s7 = 4'd7,
    s8 = 4'd8;
    
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            stage      <= s0;
            next_stage <= s0;
        end
        else stage <= next_stage;
    end
    
    always @(*) begin
        case(stage)
            s0: next_stage <= (in)? s1:s0;
            s1: next_stage <= (in)? s2:s0;
            s2: next_stage <= (in)? s2:s3;
            s3: next_stage <= (in)? s1:s4;
            s4: next_stage <= (in)? s5:s0;
            s5: next_stage <= (in)? s2:s6;
            s6: next_stage <= (in)? s7:s0;
            s7: next_stage <= (in)? s2:s8;
            s8: next_stage <= (in)? s1:s0;
            default: next_stage <= s0;
        endcase
    end
    
    always @(*) begin
        if (!rst_n)
            out = 0;
        else if (stage == s8) begin
            out = 1;
        end
        else begin
            out = 0;
        end
        
    end
 
endmodule
